<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * CourseColumn 类
 *
 * 该类表示专栏，继承自 BaseModel。
 *
 * @package YourPackage
 * @subpackage YourSubpackage
 * @extends BaseModel
 */
class CourseColumn extends BaseModel
{
    protected $guarded = [];

    protected $appends = ['userWatchSectionCount', 'userWatchRate', 'watchUserCount', 'userBuyLog', 'userHas'];

    protected $casts = [
        'resource' => 'json',
        'resource_tags' => 'json',
        'components' => 'json',
        'coupon_ids' => 'json'
    ];

    public function getResourceAttribute($v): array
    {
        if (!$v) {
            return [
                'courses' => [],
                'documents' => [],
                'learn_videos' => []
            ];
        }
        return json_decode($v, true);
    }

    /**
     * 用户已学习数量
     * @return int
     */
    public function getUserWatchSectionCountAttribute(): int
    {
        if (Auth::guard('api')->check()) {
            try {
                $learnVideoIds = $this->resource['learn_videos'];
            }catch (\Exception $e) {
                $learnVideoIds = [];
            }
            $user = Auth::guard('api')->user();
            return DB::table('user_learn_video_logs')->where('userId', Auth::guard('api')->user()->id)->whereIn('learnVideoId', $learnVideoIds)->sum('watchSectionCount');
        }
        return 0;
    }

    /**
     * @return Model|Builder|object|null
     */
    public function getUserBuyLogAttribute()
    {
        if (Auth::guard('api')->check()) {
            $log = DB::table('user_course_column_buy_logs')->where('userId', Auth::guard('api')->user()->id)->where('dataId', $this->id)->first();
            if ($log) {
                $log->expireAt = $log->expireAt ? Carbon::make($log->expireAt) : getCourseColumnExpireAt($this);
                if (Carbon::make($log->expireAt)->lt(now())) return null;
                if (Carbon::make($log->expireAt)->diffInYears(now()) > 90) $log->expireAt = '长期';
                else $log->expireAt = $log->expireAt->format('Y.m.d');
                return $log;
            }
        }
        return null;
    }

    public function getUserHasAttribute(): bool
    {
        if (Auth::guard('api')->check()) {
            //return (bool)DB::table('user_course_column_buy_logs')->where('userId', Auth::guard('api')->user()->id)->where('dataId', $this->id)->first();
            return (bool)$this->userBuyLog;
        }
        return false;
    }

    public function getUserWatchRateAttribute(): float
    {
        return 0;
    }

    /**
     * 学习用户数量
     * @return int
     */
    public function getWatchUserCountAttribute(): int
    {
        try {
            $learnVideoIds = $this->resource['learn_videos'];
        }catch (\Exception $e) {
            $learnVideoIds = [];
        }
        return DB::table('learn_videos')->whereIn('id', $learnVideoIds)->sum('learn_count');
    }
}
